<template>
  <el-dialog v-model="dialogVisible" :title="title" width="50%">
    <el-form :model="form" label-width="100px" ref="formRef">
      <el-form-item label="车名" prop="carname">
        <el-input v-model="form.carname"></el-input>
      </el-form-item>
      <el-form-item label="类型" prop="ctypeid">
        <el-select v-model="form.ctypeid" placeholder="请选择类型">
          <el-option
            v-for="type in CarTypes"
            :key="type.ctypeid"
            :label="type.ctypename"
            :value="type.ctypeid"
          ></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="品牌" prop="brandid">
        <el-select v-model="form.brandid" placeholder="请选择品牌">
          <el-option
            v-for="brand in CarBrands"
            :key="brand.brandid"
            :label="brand.brandname"
            :value="brand.brandid"
          ></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="车牌号" prop="plate">
        <el-input v-model="form.plate"></el-input>
      </el-form-item>
      <el-form-item label="价格" prop="price">
        <el-input v-model="form.price"></el-input>
      </el-form-item>
      <el-form-item label="库存" prop="status">
        <el-input v-model="form.status"></el-input>
      </el-form-item>
      <el-form-item label="车辆照片" prop="pictures">
        <el-upload
          action="#"
          :auto-upload="false"
          :on-change="handlePictureChange"
          :file-list="fileList"
          :show-file-list="false"
          :limit="1"
        >
          <el-button type="primary">点击上传</el-button>
        </el-upload>
        <el-image
          v-if="form.pictures"
          style="width: 100px; height: 100px; margin-top: 10px"
          :src="form.pictures"
          :preview-src-list="[form.pictures]"
          fit="cover"
        ></el-image>
      </el-form-item>
    </el-form>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="submitForm">确定</el-button>
      </span>
    </template>
  </el-dialog>
</template>

<script setup>
import { ref, defineProps, defineEmits, reactive, onMounted } from "vue";
import axios from "axios";
import api from "@/util/service";
import { ElMessage } from "element-plus";
import { useLoginStore } from "@/stores/userStores";
const userStore = useLoginStore();

const props = defineProps({
  title: {
    type: String,
    default: "新增车辆",
  },
  carTypes: {
    type: Array,
    default: () => [],
  },
  carBrands: {
    type: Array,
    default: () => [],
  },
});

const emit = defineEmits(["fetchCars"]);

const dialogVisible = ref(false);
const formRef = ref(null);
const form = reactive({
  ctypeid: "",
  carname: "",
  brandid: "",
  plate: "",
  pictures: "",
  price: "",
  isonline: 0,
  isdeleted: 0,
  status: 0,
  lid: userStore.getLid,
});
const openDialog = () => {
  dialogVisible.value = true;
};
//获取车辆类型和品牌
const CarTypes = ref([]); //类型
const CarBrands = ref([]); //品牌
const getCarType = async () => {
  const response = await api.get("/carTpye/selectCarTpye");
  CarTypes.value = response.data;
};
const getCarBrand = async () => {
  const response = await api.get("/carTpye/selectCarBrand");
  CarBrands.value = response.data;
};
//添加车辆
const handlePictureChange = async (file) => {
  // 检查文件是否存在
  if (!file || !file.raw) {
    ElMessage.error("未选择有效文件");
    return;
  }
  if (!userStore.username) {
    ElMessage.error("用户未登录");
    return;
  }

  const formData = new FormData();
  formData.append("file", file.raw);
  formData.append("username", userStore.username);

  try {
    // 重点：移除手动设置的 Content-Type
    const response = await axios.post(
      "http://127.0.0.1:9999/oss/updateAvatar",
      formData,
      {
        headers: {
          "Content-Type": "multipart/form-data",
        },
      }
    );

    if (response.data.code === 200) {
      form.pictures = response.data.data; // 保存返回的图片地址
      ElMessage.success("图片上传成功");
    } else {
      ElMessage.error("上传图片失败，请稍后重试");
    }
  } catch (error) {
    console.error("上传图片失败:", error);
    ElMessage.error("上传图片失败，请稍后重试");
  }
};

const submitForm = async () => {
  formRef.value.validate(async (valid) => {
    if (valid) {
      try {
        const response = await api.post("/tcar/insertCar", form);
        if (response.code === 200) {
          ElMessage.success("新增车辆成功");
          dialogVisible.value = false;
          emit("fetchCars"); // 触发父组件刷新数据
        } else {
          ElMessage.error("新增车辆失败，请稍后重试");
        }
      } catch (error) {
        console.error("新增车辆失败:", error);
        ElMessage.error("新增车辆失败，请稍后重试");
      }
    }
  });
};
onMounted(() => {
  getCarType();
  getCarBrand();
});
defineExpose({ openDialog });
</script>

<style scoped>
.el-image {
  margin-top: 10px;
}
</style>
